<template>
  <view class="permissions">
    <view class="header">
      <text class="title">权限管理</text>
      <view class="header-actions">
        <button class="btn-primary" @click="showAddRole = true">添加角色</button>
      </view>
    </view>
    
    <view class="tabs">
      <text 
        class="tab" 
        :class="{ active: activeTab === 'roles' }"
        @click="activeTab = 'roles'"
      >
        角色管理
      </text>
      <text 
        class="tab" 
        :class="{ active: activeTab === 'permissions' }"
        @click="activeTab = 'permissions'"
      >
        权限管理
      </text>
    </view>
    
    <!-- 角色管理 -->
    <view v-if="activeTab === 'roles'" class="roles-section">
      <view class="role-list">
        <view v-for="role in roles" :key="role.id" class="role-item">
          <view class="role-info">
            <text class="role-name">{{ role.displayName }}</text>
            <text class="role-desc">{{ role.description }}</text>
            <text class="role-level">级别: {{ role.level }}</text>
          </view>
          <view class="role-actions">
            <button class="btn-edit" @click="editRole(role)">编辑</button>
            <button class="btn-delete" @click="deleteRole(role.id)" v-if="!role.isSystem">删除</button>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 权限管理 -->
    <view v-if="activeTab === 'permissions'" class="permissions-section">
      <view class="permission-categories">
        <view v-for="category in permissionCategories" :key="category" class="category-section">
          <text class="category-title">{{ getCategoryName(category) }}</text>
          <view class="permission-list">
            <view 
              v-for="permission in getPermissionsByCategory(category)" 
              :key="permission.id" 
              class="permission-item"
            >
              <view class="permission-info">
                <text class="permission-name">{{ permission.displayName }}</text>
                <text class="permission-desc">{{ permission.description }}</text>
              </view>
              <view class="permission-actions">
                <button class="btn-edit" @click="editPermission(permission)">编辑</button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 添加/编辑角色弹窗 -->
    <view v-if="showAddRole || editingRole" class="modal-overlay" @click="closeRoleModal">
      <view class="modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">{{ editingRole ? '编辑角色' : '添加角色' }}</text>
          <text class="modal-close" @click="closeRoleModal">×</text>
        </view>
        <view class="modal-body">
          <view class="form-group">
            <text class="form-label">角色名称</text>
            <input class="form-input" v-model="roleForm.displayName" placeholder="请输入角色名称" />
          </view>
          <view class="form-group">
            <text class="form-label">角色描述</text>
            <textarea class="form-textarea" v-model="roleForm.description" placeholder="请输入角色描述"></textarea>
          </view>
          <view class="form-group">
            <text class="form-label">角色级别</text>
            <input class="form-input" type="number" v-model="roleForm.level" placeholder="请输入角色级别" />
          </view>
          <view class="form-group">
            <text class="form-label">权限配置</text>
            <view class="permission-checkboxes">
              <view v-for="permission in allPermissions" :key="permission.id" class="checkbox-item">
                <checkbox 
                  :checked="roleForm.permissions.includes(permission.id)"
                  @change="togglePermission(permission.id)"
                />
                <text class="checkbox-label">{{ permission.displayName }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <button class="btn-cancel" @click="closeRoleModal">取消</button>
          <button class="btn-confirm" @click="saveRole">保存</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      activeTab: 'roles',
      roles: [],
      allPermissions: [],
      showAddRole: false,
      editingRole: null,
      roleForm: {
        displayName: '',
        description: '',
        level: 0,
        permissions: []
      }
    }
  },
  
  computed: {
    permissionCategories() {
      const categories = [...new Set(this.allPermissions.map(p => p.category))]
      return categories.filter(c => c)
    }
  },
  
  onLoad() {
    this.loadRoles()
    this.loadPermissions()
  },
  
  methods: {
    async loadRoles() {
      try {
        const token = uni.getStorageSync('token')
        const res = await uni.request({
          url: 'http://localhost:3000/api/permissions/roles',
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        if (res.data.success) {
          this.roles = res.data.data || []
        }
      } catch (error) {
        console.error('加载角色失败:', error)
      }
    },
    
    async loadPermissions() {
      try {
        const token = uni.getStorageSync('token')
        const res = await uni.request({
          url: 'http://localhost:3000/api/permissions/permissions',
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        if (res.data.success) {
          this.allPermissions = res.data.data || []
        }
      } catch (error) {
        console.error('加载权限失败:', error)
      }
    },
    
    editRole(role) {
      this.editingRole = role
      this.roleForm = {
        displayName: role.displayName,
        description: role.description,
        level: role.level,
        permissions: role.permissions || []
      }
    },
    
    async deleteRole(roleId) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个角色吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const token = uni.getStorageSync('token')
              const deleteRes = await uni.request({
                url: `http://localhost:3000/api/permissions/roles/${roleId}`,
                method: 'DELETE',
                header: {
                  'Authorization': `Bearer ${token}`
                }
              })
              
              if (deleteRes.data.success) {
                uni.showToast({ title: '删除成功' })
                this.loadRoles()
              }
            } catch (error) {
              uni.showToast({ title: '删除失败', icon: 'none' })
            }
          }
        }
      })
    },
    
    closeRoleModal() {
      this.showAddRole = false
      this.editingRole = null
      this.roleForm = {
        displayName: '',
        description: '',
        level: 0,
        permissions: []
      }
    },
    
    async saveRole() {
      try {
        const token = uni.getStorageSync('token')
        const url = this.editingRole 
          ? `http://localhost:3000/api/permissions/roles/${this.editingRole.id}`
          : 'http://localhost:3000/api/permissions/roles'
        
        const res = await uni.request({
          url,
          method: this.editingRole ? 'PUT' : 'POST',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          data: this.roleForm
        })
        
        if (res.data.success) {
          uni.showToast({ title: '保存成功' })
          this.closeRoleModal()
          this.loadRoles()
        }
      } catch (error) {
        uni.showToast({ title: '保存失败', icon: 'none' })
      }
    },
    
    togglePermission(permissionId) {
      const index = this.roleForm.permissions.indexOf(permissionId)
      if (index > -1) {
        this.roleForm.permissions.splice(index, 1)
      } else {
        this.roleForm.permissions.push(permissionId)
      }
    },
    
    getCategoryName(category) {
      const categoryNames = {
        'user': '用户管理',
        'order': '订单管理',
        'product': '产品管理',
        'ad': '广告管理',
        'system': '系统管理'
      }
      return categoryNames[category] || category
    },
    
    getPermissionsByCategory(category) {
      return this.allPermissions.filter(p => p.category === category)
    },
    
    editPermission(permission) {
      // 编辑权限功能
      uni.showToast({ title: '权限编辑功能开发中', icon: 'none' })
    }
  }
}
</script>

<style scoped>
.permissions {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.btn-primary {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.tabs {
  display: flex;
  background: white;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}

.tab {
  flex: 1;
  text-align: center;
  padding: 24rpx;
  font-size: 28rpx;
  color: #666;
  border-radius: 12rpx;
}

.tab.active {
  background-color: #007bff;
  color: white;
}

.role-list, .permission-list {
  background: white;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}

.role-item, .permission-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.role-item:last-child, .permission-item:last-child {
  border-bottom: none;
}

.role-info, .permission-info {
  flex: 1;
}

.role-name, .permission-name {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.role-desc, .permission-desc {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.role-level {
  font-size: 24rpx;
  color: #999;
}

.role-actions, .permission-actions {
  display: flex;
  gap: 16rpx;
}

.btn-edit {
  background-color: #28a745;
  color: white;
  border: none;
  padding: 12rpx 24rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
}

.btn-delete {
  background-color: #dc3545;
  color: white;
  border: none;
  padding: 12rpx 24rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
}

.category-section {
  margin-bottom: 40rpx;
}

.category-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 12rpx;
  width: 90%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.modal-close {
  font-size: 48rpx;
  color: #999;
  cursor: pointer;
}

.modal-body {
  padding: 30rpx;
}

.form-group {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 12rpx;
}

.form-input, .form-textarea {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.form-textarea {
  height: 120rpx;
  resize: vertical;
}

.permission-checkboxes {
  max-height: 400rpx;
  overflow-y: auto;
}

.checkbox-item {
  display: flex;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.checkbox-label {
  margin-left: 16rpx;
  font-size: 28rpx;
  color: #333;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #eee;
}

.btn-cancel {
  background-color: #6c757d;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.btn-confirm {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}
</style>